export function useScreenSize() {
  const sizeRange = ref([20, 40, 60, 80, 100, 150, 200, 300, 400])
  const paddingToolsWidth = ref(18)
  const currentSizeRangeIndex = ref(-1)
  const bigscreenWidth = ref(1920)
  const bigscreenHeight = ref(1080)
  const scaleNum = ref(0)

  const bodyWidth = computed(() => document.body.clientWidth)
  const bodyHeight = computed(() => document.body.clientHeight)

  const middleWidth = computed(() => {
    return bodyWidth.value - 500
  })

  const middleHeight = computed(() => bodyHeight.value)

  const bigscreenScaleInWorkbench = computed(() => {
    const widthScale = (middleWidth.value - paddingToolsWidth.value) / bigscreenWidth.value
    const heightScale = (middleHeight.value - paddingToolsWidth.value) / bigscreenHeight.value
    return Math.min(widthScale, heightScale)
  })

  const step = computed(() => Number(100 / (bigscreenScaleInWorkbench.value * 100)))

  const defaultSize = computed(() => {
    const obj: any = { index: -1, size: '50' }
    sizeRange.value.forEach((item, index) => {
      if (item <= 100 * bigscreenScaleInWorkbench.value) {
        obj.index = index
        obj.size = 100 * bigscreenScaleInWorkbench.value
      }
    })
    if (obj.index === -1) {
      obj.index = 0
      obj.size = sizeRange[0]
    }
    return obj
  })

  const setSize = (num) => {
    switch (num) {
      case 0:
        currentSizeRangeIndex.value =
          currentSizeRangeIndex.value === 0 ? 0 : (currentSizeRangeIndex.value -= 1)
        break
      case 1:
        currentSizeRangeIndex.value =
          currentSizeRangeIndex.value === 8 ? 8 : (currentSizeRangeIndex.value += 1)
        break
      case 2:
        currentSizeRangeIndex.value = defaultSize.value.index
    }
    scaleNum.value =
      currentSizeRangeIndex.value === defaultSize.value.index
        ? defaultSize.value.size
        : sizeRange.value[currentSizeRangeIndex.value]
  }

  const workbenchTransform = computed(
    () => `scale(${bigscreenScaleInWorkbench.value}, ${bigscreenScaleInWorkbench.value})`
  )

  watch(
    defaultSize,
    (val) => {
      if (val !== -1) {
        currentSizeRangeIndex.value = val.index
        scaleNum.value = val.size
      }
    },
    { immediate: true }
  )

  return {
    sizeRange,
    bigscreenWidth,
    bigscreenHeight,
    paddingToolsWidth,
    currentSizeRangeIndex,
    bigscreenScaleInWorkbench,
    workbenchTransform,
    defaultSize,
    scaleNum,
    setSize,
    step
  }
}
